package org.chmodke.proxy.client.auth;

import org.chmodke.proxy.client.ProxyCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Authenticator;
import java.net.PasswordAuthentication;

/**
 * @author kehao
 */
public class GlobalAuthenticator extends Authenticator {
    private static final Logger logger = LoggerFactory.getLogger(GlobalAuthenticator.class);

    private GlobalAuthenticator() {
    }

    public static GlobalAuthenticator getInstance() {
        return INNER.instance;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        String host = getRequestingHost();
        int port = getRequestingPort();
        logger.debug("query auth for proxy {}:{}.", host, port);
        PasswordAuthentication auth = ProxyCenter.getInstance().getAuth(host, port);
        if (null != auth) {
            logger.debug("found auth for proxy {}:{}.", host, port);
        }
        return auth;
    }

    private static class INNER {
        private static final GlobalAuthenticator instance = new GlobalAuthenticator();
    }
}
